package com.jjlin.chapter_2;

import java.util.*;
public class CD137{
    public static class Node{
        public int val;
        public Node next;
        public Node(int data){
            this.val = data;
        }
    }

    public static Node createNodeList(int[] nums){
        if(nums == null || nums.length < 1)
            return null;
        Node head = new Node(nums[0]);
        Node pre = head;
        for(int i = 1; i < nums.length; i++){
            Node cur = new Node(nums[i]);
            pre.next = cur;
            pre = cur;
        }
        return head;
    }

    public static void printNodeList(Node head){
        Node cur = head;
        while(cur != null){
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    //解法1：利用hashSet来检查节点数值是否重复，时间复杂度为O(N)，空间复杂度为O(N)
    public static void removeRepeatNode(Node head){
        if(head == null || head.next == null)
            return;
        HashSet<Integer> set = new HashSet<>();
        set.add(head.val);
        Node cur = head.next;
        Node pre = head;
        while(cur != null){
            if(!set.contains(cur.val)){
                set.add(cur.val);
                pre.next = cur;
                pre = cur;
            }
            cur = cur.next;
        }
        pre.next = null;//别忘了这一步
    }

    //解法2：依次删除每个节点的值重复的节点，时间复杂度为O(N^2)，空间复杂度为O(1)，这个时间在牛客上过不了
    public static void removeRepeatNode1(Node head){
        if(head == null || head.next == null)
            return;
        Node cur = head;
        Node pre = null;
        Node next = null;
        while(cur != null){
            pre = cur;
            next = cur.next;
            while(next != null){
                if(next.val != cur.val){
                    pre = next;
                }else{//删除值重复的节点
                    pre.next = next.next;
                }
                next = next.next;
            }
            cur = cur.next;
        }
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0; i < n; i++)
            nums[i] = sc.nextInt();
        Node head = createNodeList(nums);
        removeRepeatNode(head);
        printNodeList(head);
    }
}
